# -*- coding: UTF-8 -*-

import ddddocr

from .tools import get_logger

__all__ = [
    'ocr', 'det',
    'get_verify_code_result', 'get_verify_code'
]

logger = get_logger(__name__)

det = ddddocr.DdddOcr(show_ad=False, beta=True, det=True)
ocr = ddddocr.DdddOcr(show_ad=False, beta=True)


def get_verify_code_result(image):
    if isinstance(image, str):
        with open(image, 'rb') as f:
            image = f.read()

    res = ocr.classification(image)
    logger.debug(f'图片识别结果：{res}')
    if res is not None:
        m = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10}
        f = {
            '加': lambda x, y: x + y,
            '减': lambda x, y: x - y,
            '乘': lambda x, y: x * y,
            '除': lambda x, y: x / y,
        }
        try:
            return int(f.get(res[1])(m.get(res[0]), m.get(res[2])))
        except Exception as e:
            logger.debug(e)


def get_verify_code(image):
    if isinstance(image, str):
        with open(image, 'rb') as f:
            image = f.read()

    res = ocr.classification(image)
    logger.debug(f'图片识别结果：{res}')
    return res
